<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { CustomSearch } from '@/components/CustomSearch'
import { Table, TableColumn } from '@/components/Table'
import { ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted, computed, watch, h, nextTick } from 'vue'
import { FormSchema } from '@/components/Form'
import { ChatSidebarPanel } from '@/components/IntelligentChat'
import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ElTag, ElMessage, ElUpload, ElButton, ElDialog, ElIcon } from 'element-plus'
import { BaseButton } from '@/components/Button'
import { useRouter } from 'vue-router'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import {
  queryQtyChargArchInfo,
  importData,
  downloadTemplate as downloadTemplateApi,
  addAbnormalRecognition,
  updateAbnormalRecognition
} from '@/api/electricityAbnormal'
import { RECOGNITION_API } from '@/api/electricityApi'
import {
  sendMessageToDify,
  DifyRequest,
  DifyConfig,
  stopDifyConfig,
  stopDifyRequest,
  stopMessageToDify
} from '@/api/dify'
import { useUserStoreWithOut } from '@/store/modules/user'
import axios, { AxiosError } from 'axios'
import { custClsOptions, ecCategOptions, deregAttrTypeOptions, abnorCategEROptions } from '@/dicts'
import { size } from 'lodash-es'
import dayjs from 'dayjs'
import { DIFY_API_V1_URL, DIFY_API_KEY, DIFY_API_BASE_URL } from '@/constants/dify'
import { Icon } from '@/components/Icon'

const { t } = useI18n()
const router = useRouter()

interface ChatSidebarInstance extends ComponentPublicInstance {
  openDrawer: () => void
  closeDrawer: () => void
}

const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData, setValues } = searchMethods

const selectedRows = ref<any[]>([])

const getPreviousMonthRange = () => {
  const currentDate = dayjs()
  const previousMonth = currentDate.subtract(1, 'month')
  const previousMonthStr = previousMonth.format('YYYYMM')
  return [previousMonthStr, previousMonthStr]
}

const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  },
  {
    field: 'expYm',
    label: '量费年月',
    component: 'DatePicker',
    componentProps: {
      type: 'monthrange',
      valueFormat: 'YYYYMM',
      startPlaceholder: '开始年月',
      endPlaceholder: '结束年月'
    },
    value: getPreviousMonthRange()
  },
  {
    field: 'abnorCateg',
    label: '异常类型',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择异常类型',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: abnorCategEROptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'ecCateg',
    label: '用电类别',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择用电类别',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: ecCategOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'deregAttrCls',
    label: '市场化属性分类',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择市场化属性分类',
      props: {
        checkStrictly: false,
        emitPath: false,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: deregAttrTypeOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  }
])

interface IResponse<T> {
  code: number
  data: T
  message: string
}

interface TableRow {
  id: string
  [key: string]: any
}

const selectable = (row: TableRow) => {
  return row.rectStat !== '2'
}

const columns: TableColumn[] = [
  {
    field: '',
    type: 'selection',
    width: 60,
    selectable: selectable
  },
  {
    field: 'index',
    type: 'index',
    label: '序号',
    width: 60,
    fixed: 'left'
  },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    width: 180,
    fixed: 'left'
  },
  {
    field: 'expYm',
    label: '量费年月',
    width: 120
  },
  {
    field: 'abnorType',
    label: '异常类别',
    width: 120
  },
  {
    field: 'abnorCateg',
    label: '异常类型',
    width: 120
  },
  {
    field: 'abnorDtlInfo',
    label: '异常说明',
    width: 200
  },
  {
    field: 'planNo',
    label: '计划编号',
    width: 180
  },
  {
    field: 'custNo',
    label: '用户编号',
    width: 180
  },
  {
    field: 'custName',
    label: '用户名称',
    minWidth: 210
  },
  {
    field: 'custClsName',
    label: '客户分类',
    width: 120
  },
  {
    field: 'deregAttrClsName',
    label: '市场化属性分类',
    width: 150
  },
  {
    field: 'action',
    label: '操作',
    width: 130,
    fixed: 'right',
    slots: {
      default: (data: any) => {
        return h(
          BaseButton,
          {
            type: 'primary',
            link: true,
            onClick: () => openDetailDialog(data.row)
          },
          '查看详情'
        )
      }
    }
  }
]

const { tableRegister, tableMethods, tableState } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    try {
      const formData = await getFormData()
      console.log('formData', formData)
      if (formData.ecCateg && formData.ecCateg.length !== 0) {
        formData.ecCateg = formData.ecCateg.flat()
      } else {
        formData.ecCateg = []
      }
      const requestParams = {
        startExpYm: formData.expYm?.[0],
        endExpYm: formData.expYm?.[1],
        abnorTypeList: formData.abnorCateg?.map((item) => item[0] || ''),
        abnorCategList:
          formData.abnorCateg?.length > 0 ? formData.abnorCateg?.map((item) => item[1] || '') : [],
        deregAttrCls: formData.deregAttrCls,
        ecCateg: formData.ecCateg,
        mgtOrgName: formData.mgtOrgName,
        pageSize: tableState.pageSize.value,
        pageNum: tableState.currentPage.value,
        custNo: formData.custNo
      }
      formData.abnorCateg?.map((item) => {
        if (item[0] == '全部') {
          requestParams.abnorTypeList = []
          requestParams.abnorCategList = []
        } else if (item[0] == '无异常') {
          requestParams.abnorCategList = []
        }
      })

      console.log('发送API请求参数:', JSON.stringify(requestParams))
      console.log('请求URL:', RECOGNITION_API.QUERY_INFO)

      const response = await queryQtyChargArchInfo(requestParams)
      console.log('API响应数据:', response)

      if (response) {
        let list: any[] = []
        let total = 0

        if (response.data) {
          const responseData = response.data

          if (Array.isArray(responseData)) {
            list = responseData
            total = (response as any).total || responseData.length || 0
          } else if (typeof responseData === 'object') {
            if (responseData.list && Array.isArray(responseData.list)) {
              list = responseData.list
              total = responseData.total || responseData.list.length || 0
            } else if (responseData.records && Array.isArray(responseData.records)) {
              list = responseData.records
              total = responseData.total || responseData.records.length || 0
            } else if (responseData.data && Array.isArray(responseData.data)) {
              list = responseData.data
              total = responseData.total || responseData.data.length || 0
            } else if (responseData.rows && Array.isArray(responseData.rows)) {
              list = responseData.rows
              total = responseData.total || responseData.rows.length || 0
            } else {
              list = [responseData]
              total = 1
            }

            if (!total && typeof responseData.totalCount === 'number') {
              total = responseData.totalCount
            } else if (!total && typeof responseData.count === 'number') {
              total = responseData.count
            }
          }
        } else if (Array.isArray(response)) {
          list = response
          total = response.length
        } else if (typeof response === 'object') {
          const resp = response as any
          if (resp.list && Array.isArray(resp.list)) {
            list = resp.list
            total = resp.total || resp.list.length || 0
          } else if (resp.records && Array.isArray(resp.records)) {
            list = resp.records
            total = resp.total || resp.records.length || 0
          } else if (resp.data && Array.isArray(resp.data)) {
            list = resp.data
            total = resp.total || resp.data.length || 0
          } else if (resp.rows && Array.isArray(resp.rows)) {
            list = resp.rows
            total = resp.total || resp.rows.length || 0
          }

          if (!total && typeof resp.totalCount === 'number') {
            total = resp.totalCount
          } else if (!total && typeof resp.count === 'number') {
            total = resp.count
          }
        }

        console.log('处理后的数据:', list.length, '条, 总数:', total)

        return {
          list,
          total
        }
      }

      return {
        list: [],
        total: 0
      }
    } catch (error: any) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败: ' + (error instanceof Error ? error.message : '未知错误'))
      return {
        list: [],
        total: 0
      }
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

const handleSearch = async () => {
  const formData = await getFormData()
  console.log('搜索条件:', formData)

  currentPage.value = 1

  refresh()
}

const handleReset = async () => {
  currentPage.value = 1
  refresh()
}

const { setProps } = tableMethods

onMounted(() => {
  if (searchRef.value) {
    searchRegister(searchRef.value)

    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })

    setValues({
      expYm: getPreviousMonthRange()
    })
  }
  setProps({
    height: 438
  })
  refresh()
})

watch(
  () => getFormData(),
  () => {
    console.log('搜索条件已变更')
  },
  { deep: true }
)

const chatSidebarRef = ref<ChatSidebarInstance | null>(null)
const aiInputs = ref({})
const aiAnalysisResult = ref<any>(null)
const detailsContent = ref<any>(null)

const handleAiFinish = (result: any) => {
  console.log('AI会话结束:', result)
  if (result.extractedJson) {
    aiAnalysisResult.value = result.extractedJson
    console.log('电费异常分析结果:', aiAnalysisResult.value)

    ElMessage.success('已提取分析结果')
  }

  if (result.detailsContent) {
    detailsContent.value = result.detailsContent
    console.log('提取的details内容:', detailsContent.value)
    submitAnalysisToBackend()
  }
}

const handleDetailsExtracted = (details: any) => {
  detailsContent.value = details
  console.log('从AI对话中提取的details内容:', details)
}

const submissionData = reactive<any>({})

const submitAnalysisToBackend = async () => {
  if (!detailsContent.value) {
    ElMessage.warning('没有可提交的分析结果')
    return
  }

  try {
    const afterRecognitionData = JSON.parse(detailsContent.value)
    console.log('识别后的数据:======》', afterRecognitionData)

    submissionData.value = afterRecognitionData.map((originalItem) => {
      return {
        qtyChargArchInfoId: originalItem.qtyChargArchInfoId,
        // 将 abnormal_level1.name 赋值给 abnorType
        abnorType: originalItem.abnormal_level1?.name || originalItem.abnorType,
        // 将 abnormal_level2.name 赋值给 abnorCateg
        abnorCateg: originalItem.abnormal_level2?.name || originalItem.abnorCateg,
        // 将 root_cause 赋值给 abnorDtlInfo
        abnorDtlInfo: originalItem.root_cause || originalItem.abnorDtlInfo,
        rectSug: originalItem.rectSug || originalItem.rectSug,
        rectStat: abnorCateg === '无异常' ? '10' : '01'
      }
    })
    console.log('提交处理后的分析结果到后端的数据:======》', submissionData.value)
    const res = (await addAbnormalRecognition(submissionData.value)) as IResponse<any>
    if (res && res.code === 200) {
      ElMessage.success('提交成功')
      refresh()
    }
  } catch (error) {
    console.error('提交分析结果失败:', error)
    ElMessage.error('提交分析结果失败，请重试')
  }
}

const handleBeforeOpen = () => {
  chatSidebarRef.value?.openDrawer()
  const structuredData = selectedRows.value.map((row) => {
    const { abnorType, abnorCateg, abnorDtlInfo, ...restData } = { ...row }
    return restData
  })

  aiInputs.value = {
    table_data: JSON.stringify(structuredData)
  }

  return true
}

const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

const openDetailDialog = (row: any) => {
  currentDetail.value = {
    ...row
  }
  detailDialogVisible.value = true
}

const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

const importDialogVisible = ref(false)
const importing = ref(false)
const selectedFile = ref<File | null>(null)

const showImportDialog = () => {
  importDialogVisible.value = true
  selectedFile.value = null
}

const handleFileChange = (file: any) => {
  const isExcel =
    file.raw.type === 'application/vnd.ms-excel' ||
    file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！')
    return false
  }

  selectedFile.value = file.raw
  return true
}

const handleFileRemove = () => {
  selectedFile.value = null
}

const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }

  importing.value = true

  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)

    const res = await importData(formData)
    console.log('导入响应:', res)

    if (res && typeof res === 'object' && 'success' in res) {
      if (res.success === true) {
        ElMessage.success(`成功导入数据`)
        importDialogVisible.value = false

        refresh()
      } else {
        ElMessage.error(res?.data?.msg || res?.data?.message || '导入失败，请检查文件格式是否正确')
      }
    }
  } catch (error) {
    console.error('导入处理出错:', error)
    ElMessage.error('导入处理出错，请重试')
  } finally {
    importing.value = false
  }
}

const downloadTemplate = async (event: Event) => {
  event.preventDefault()
  event.stopPropagation()

  try {
    ElMessage.info('正在下载模板...')

    const res = await downloadTemplateApi()

    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = '电费数据导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败，请重试')
  }
}

const openInitConfirmDialog = () => {
  ElMessageBox.confirm('是否确认初始化？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      handleInit()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '初始化已取消'
      })
    })
}

const ELECTRICITY_API_URL = import.meta.env.VITE_ELECTRICITY_API_URL

const handleInit = async () => {
  try {
    ElMessage({
      message: '正在初始化系统，请稍候...',
      type: 'info',
      duration: 2000
    })
    const formData = await getFormData()
    console.log('formData', formData)
    if (formData.ecCateg && formData.ecCateg.length !== 0) {
      formData.ecCateg = formData.ecCateg.flat()
    } else {
      formData.ecCateg = []
    }
    const requestParams = {
      startExpYm: formData.expYm?.[0],
      endExpYm: formData.expYm?.[1],
      abnorTypeList: formData.abnorCateg?.map((item) => item[0] || ''),
      abnorCategList:
        formData.abnorCateg?.length > 0 ? formData.abnorCateg?.map((item) => item[1] || '') : [],
      deregAttrCls: formData.deregAttrCls,
      ecCateg: formData.ecCateg,
      mgtOrgName: formData.mgtOrgName,
      custNo: formData.custNo
    }
    formData.abnorCateg?.map((item) => {
      if (item[0] == '全部') {
        requestParams.abnorTypeList = []
        requestParams.abnorCategList = []
      } else if (item[0] == '无异常') {
        requestParams.abnorCategList = []
      }
    })

    console.log('发送API请求参数:', JSON.stringify(requestParams))

    const response = await axios.post(`${ELECTRICITY_API_URL}/api/users/deleteQtyChargArchInfo`, {
      ...requestParams
    })

    if (response.status === 200 && response.data) {
      refresh()
      ElMessage({
        message: '初始化成功!',
        type: 'success',
        duration: 2000
      })

      setTimeout(() => {
        router.push('/electricityAbnormal/import')
      }, 3000)
    } else {
      ElMessage.error('初始化失败，请重试')
    }
  } catch (error) {
    console.error('初始化过程出错:', error)
    ElMessage.error('初始化过程出错: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

const resetButtonVisible = ref(true)

const rectStatMap = {
  '00': '未处理',
  '01': '未处理',
  '02': '处理中',
  '03': '已处理',
  '04': '无需处理',
  '10': '无异常'
}

const getRectStatName = (code: string) => {
  return rectStatMap[code] || '未知状态'
}

const aiResponseMessage = ref('')
const isProcessingAI = ref(false)

const openAIDialog = () => {
  detailDialogVisible.value = true
}

const closeAiDialog = () => {
  detailDialogVisible.value = false
  aiResponseMessage.value = ''
}

const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}
</script>

<template>
  <ContentWrap title="电费异常识别" message="对站点电费进行异常识别和处理">
    <CustomSearch
      :schema="schema"
      :layout="'bottom'"
      :button-position="'right'"
      :custom-buttons="[
        {
          label: '导入数据',
          type: 'success',
          plain: true,
          icon: 'vi-ep:upload-filled',
          color: '#286af6',
          onClick: showImportDialog
        },
        {
          label: '异常识别',
          type: 'success',
          icon: 'vi-ep:chat-dot-square',
          loading: isProcessingAI,
          color: '#286af6',
          onClick: openAIDialog
        },
        {
          label: '初始化',
          type: 'primary',
          icon: 'vi-ep:refresh',
          color: '#ff6b35',
          onClick: openInitConfirmDialog
        }
      ]"
      @search="handleSearch"
      @reset="handleReset"
      ref="searchRef"
    />
    <div>总计：{{ total }}条数据</div>
    <div class="table-container">
      <Table
        ref="tableRef"
        v-model:pageSize="pageSize"
        v-model:currentPage="currentPage"
        :columns="columns"
        :data="dataList"
        :fit="true"
        row-key=""
        :loading="loading"
        :pagination="{
          total,
          pageSize,
          currentPage,
          pageSizes: [10, 20, 50, 100],
          background: true
        }"
        height="238.8"
        style="
          width: 100%;
          --el-table-border-color: #cdd7d5;
          --el-table-text-color: #171717;
          --el-table-header-text-color: #585858;
        "
        :header-cell-style="{
          background: '#e5f5f3',
          color: '#585858'
        }"
        :rowStyle="tableRowStyle"
        @register="tableRegister"
        @refresh="refresh"
        @selection-change="handleSelectionChange"
      />
    </div>
    <ElDialog v-model="importDialogVisible" title="导入数据" width="500px" destroy-on-close>
      <div class="import-dialog-content">
        <ElUpload
          class="upload-wrapper"
          drag
          action="#"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          accept=".xls,.xlsx"
        >
          <ElIcon class="upload-icon">
            <Icon icon="vi-ep:upload-filled" />
          </ElIcon>
          <div class="upload-text">
            <span>将文件拖到此处，或<em>点击上传</em></span>
            <div class="upload-tip">支持 .xls, .xlsx 格式文件</div>
          </div>
        </ElUpload>

        <div class="import-actions">
          <a href="#" @click="downloadTemplate" class="template-link">
            <Icon icon="vi-ep:download" class="mr-5px" />
            下载导入模板
          </a>
          <div class="action-buttons">
            <ElButton @click="importDialogVisible = false">取 消</ElButton>
            <ElButton type="primary" @click="handleImport" :loading="importing"> 导 入 </ElButton>
          </div>
        </div>
      </div>
    </ElDialog>

    <ChatSidebarPanel
      ref="chatSidebarRef"
      :api-key="DIFY_API_KEY"
      :api-base="DIFY_API_V1_URL"
      :inputs="aiInputs"
      title="电费异常识别助手"
      placeholder="请输入您想了解的问题..."
      welcome-message="您好！我是电费异常识别助手。我可以帮您分析电费异常问题，提供解决方案。请问有什么需要帮助的吗？"
      @message-end="handleAiFinish"
      @before-open="handleBeforeOpen"
      :show-float-button="true"
    />

    <ElDialog
      v-model="detailDialogVisible"
      title="详情"
      width="70%"
      :before-close="closeDetailDialog"
      destroy-on-close
      class="detail-dialog"
      style=""
    >
      <div class="detail-container">
        <div class="detail-section">
          <div class="detail-title">异常信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">异常类别：</div>
              <div class="detail-value">{{ currentDetail?.abnorType }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">异常类型：</div>
              <div class="detail-value">{{ currentDetail?.abnorCateg }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">异常说明：</div>
              <div class="detail-value">{{ currentDetail?.abnorDtlInfo }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">算费信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">量费年月：</div>
              <div class="detail-value">{{ currentDetail?.expYm }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">计划编号：</div>
              <div class="detail-value">{{ currentDetail?.planNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">核算包编号：</div>
              <div class="detail-value">{{ currentDetail?.bilgUnitNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">本次抄见量：</div>
              <div class="detail-value">{{ currentDetail?.thisMrQty }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">总结算量：</div>
              <div class="detail-value">{{ currentDetail?.tSettleQty }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">总结算费：</div>
              <div class="detail-value">{{ currentDetail?.tSettleExp }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">本次抄见量</div>
          <div class="reading-table-container">
            <table class="reading-table">
              <thead>
                <tr>
                  <td class="table-label">示数类型</td>
                  <td v-if="currentDetail?.zxygReadType" class="table-header">正向有功（总）</td>
                  <td v-if="currentDetail?.zxygjfReadType" class="table-header"
                    >正向有功（尖峰）</td
                  >
                  <td v-if="currentDetail?.zxygfReadType" class="table-header">正向有功（峰）</td>
                  <td v-if="currentDetail?.zxyggReadType" class="table-header">正向有功（谷）</td>
                  <td v-if="currentDetail?.zxygpReadType" class="table-header">正向有功（平）</td>
                  <td v-if="currentDetail?.zxwgReadType" class="table-header">正向无功（总）</td>
                  <td v-if="currentDetail?.wgReadType" class="table-header">无功（Q4象限）</td>
                  <td v-if="currentDetail?.zdxlReadType" class="table-header">最大需量</td>
                  <td v-if="currentDetail?.fxwgReadType" class="table-header">反向无功（总）</td>
                  <td v-if="currentDetail?.fxygReadType" class="table-header">反向有功（总）</td>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td class="table-label">抄见电量</td>
                  <td v-if="currentDetail?.zxygReadType" class="table-cell">{{
                    currentDetail?.zxygReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxygjfReadType" class="table-cell">{{
                    currentDetail?.zxygjfReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxygfReadType" class="table-cell">{{
                    currentDetail?.zxygfReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxyggReadType" class="table-cell">{{
                    currentDetail?.zxyggReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxygpReadType" class="table-cell">{{
                    currentDetail?.zxygpReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zxwgReadType" class="table-cell">{{
                    currentDetail?.zxwgReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.wgReadType" class="table-cell">{{
                    currentDetail?.wgReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.zdxlReadType" class="table-cell">{{
                    currentDetail?.zdxlReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.fxwgReadType" class="table-cell">{{
                    currentDetail?.fxwgReadTypeNameDl || '-'
                  }}</td>
                  <td v-if="currentDetail?.fxygReadType" class="table-cell">{{
                    currentDetail?.fxygReadTypeNameDl || '-'
                  }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">基础档案信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">管理单位：</div>
              <div class="detail-value">{{ currentDetail?.mgtOrgName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">用户编号：</div>
              <div class="detail-value">{{ currentDetail?.custNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">用户名称：</div>
              <div class="detail-value">{{ currentDetail?.custName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">客户分类：</div>
              <div class="detail-value">{{ currentDetail?.custClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">市场化属性分类：</div>
              <div class="detail-value">{{ currentDetail?.deregAttrClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">合同容量：</div>
              <div class="detail-value">{{ currentDetail?.ctrtCap }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">运行容量：</div>
              <div class="detail-value">{{ currentDetail?.runCap }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">用电类别：</div>
              <div class="detail-value">{{ currentDetail?.ecCategName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">行业分类：</div>
              <div class="detail-value">{{ currentDetail?.indClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">价格码：</div>
              <div class="detail-value">{{ currentDetail?.prcCode }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">定价策略类型：</div>
              <div class="detail-value">{{ currentDetail?.prcStTypeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">基本电费计算方式：</div>
              <div class="detail-value">{{ currentDetail?.becCalcModeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">功率因数考核标准：</div>
              <div class="detail-value">{{ currentDetail?.pfStdName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">功率因数考核方式：</div>
              <div class="detail-value">{{ currentDetail?.pfEvalModeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">电压等级：</div>
              <div class="detail-value">{{ currentDetail?.voltage }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section">
          <div class="detail-title">计量点信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">安装点状态：</div>
              <div class="detail-value">{{ currentDetail?.instStatName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">安装点编号：</div>
              <div class="detail-value">{{ currentDetail?.instNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">安装点容量：</div>
              <div class="detail-value">{{ currentDetail?.instCap }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">计量方式：</div>
              <div class="detail-value">{{ currentDetail?.meterModeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">安装点用途分类：</div>
              <div class="detail-value">{{ currentDetail?.instUsageClsName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">能源计算方式：</div>
              <div class="detail-value">{{ currentDetail?.eCalcModeCodeName }}</div>
            </div>
          </div>
        </div>
        <div class="detail-section-end">
          <div class="detail-title">设备信息</div>
          <div class="detail-info">
            <div class="detail-item">
              <div class="detail-label">表计设备编号：</div>
              <div class="detail-value">{{ currentDetail?.mrDevNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">表计类型：</div>
              <div class="detail-value">{{ currentDetail?.devTypeName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">损耗编号：</div>
              <div class="detail-value">{{ currentDetail?.lossNo }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">变损计算方式：</div>
              <div class="detail-value">{{ currentDetail?.lossAlgFlagName }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">调压设备编码：</div>
              <div class="detail-value">{{ currentDetail?.adjDevNo }}</div>
            </div>
          </div>
        </div>
      </div>
    </ElDialog>
  </ContentWrap>
</template>

<style scoped>
.ml-2 {
  margin-left: 8px;
}

.mb-10px {
  margin-bottom: 10px;
}

.search-container {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.search-buttons {
  margin-left: 16px;
  margin-bottom: 16px;
}

.table-operations {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.operation-button {
  margin-left: 8px;
}

.table-container {
  margin-top: 10px;
  width: 100%;
  overflow-x: auto;
}

.view-detail-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
}

.view-detail-link:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .table-operations {
    flex-direction: column;
    align-items: flex-start;
  }

  .operation-button {
    margin-left: 0;
    margin-top: 8px;
  }

  .search-buttons {
    margin-left: 0;
    margin-top: 8px;
  }

  .floating-button {
    right: 10px;
    bottom: 60px;
  }
}

.detail-dialog :deep(.el-dialog__header) {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

.detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.import-dialog-content {
  padding: 20px;
}

.upload-wrapper {
  width: 100%;
  margin-bottom: 20px;
}

.upload-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.import-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.template-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.template-link:hover {
  color: #66b1ff;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.analysis-result-container {
  margin-top: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eaeaea;
}

.analysis-result-container h3 {
  margin-top: 0;
  color: #303133;
  font-size: 18px;
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.result-section {
  margin-bottom: 20px;
}

.result-section h4 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 12px;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.stat-item {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-label {
  color: #909399;
  font-size: 13px;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  color: #303133;
  font-weight: bold;
}

.abnormal-item {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
}

.abnormal-type {
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 8px;
}

.abnormal-description {
  margin-bottom: 8px;
  line-height: 1.5;
}

.abnormal-suggestion {
  color: #67c23a;
  font-style: italic;
  border-left: 3px solid #67c23a;
  padding-left: 10px;
  margin-top: 8px;
}

.detail-container {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  background-color: #f2f2f2;
  padding: 26px 6px 26px 26px;
}

.detail-section {
  padding: 6px;
  border-bottom: 1px solid #999;
}

.detail-section-end {
  padding: 6px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 4px;
  margin-bottom: 6px;
}

.detail-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 0 0 0 70px;
}

.detail-item {
  width: 33.333%;
  min-height: 30px;
  display: flex;
  padding: 10px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

.reading-table-container {
  padding: 0 0 0 70px;
  margin-top: 10px;
}

.reading-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

.reading-table thead {
}

.reading-table .table-label {
  font-weight: bold;
  color: #303133;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  min-width: 80px;
}

.reading-table .table-header {
  font-weight: bold;
  color: #606266;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  font-size: 13px;
  white-space: nowrap;
}

.reading-table .table-cell {
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  color: #303133;
  white-space: nowrap;
}
</style>
